package com.lbd;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 对象池。管理Map和List对象资源，减缓重复创建对象对性能开销和JVM内存的压力
 *
 * @author: linbd
 * @date: 2022/12/19 15:23
 */
public class ObjectPool {
    private static ConcurrentLinkedQueue<List<User>> listBasicCdnPools = new ConcurrentLinkedQueue<>();
    private static ConcurrentLinkedQueue<Map<Integer, List<User>>> mapsListBasicCDNPools = new ConcurrentLinkedQueue<>();


    public static void getSize() {
        System.out.println("=======> MapListBasicCDN 对象池长度 " + mapsListBasicCDNPools.size());
        System.out.println("=======> listBasicCdnPools 对象池长度 " + listBasicCdnPools.size());
    }

    /**
     * 获取对象
     *
     * @return
     */
    public static Map<Integer, List<User>> getMapListBasicCDN() {
        System.out.println("=======> MapListBasicCDN 对象池长度 " + mapsListBasicCDNPools.size());
        Map<Integer, List<User>> map = mapsListBasicCDNPools.poll();
        if (map == null) {
            map = new HashMap<>();
        }
        map.clear();
        return map;
    }

    /**
     * 回收对象
     *
     * @param objectMap
     */
    public static void offerMapListBasicCDN(Map<Integer, List<User>> objectMap) {
        if (objectMap != null) {
            objectMap.clear();
            mapsListBasicCDNPools.offer(objectMap);
            System.out.println("=======>offer pool MapListBasicCDN 对象池长度 " + mapsListBasicCDNPools.size());
        }
    }

    /**
     * 获取对象
     *
     * @return
     */
    public static List<User> getListBasicCdnObj() {
        System.out.println("=======> listBasicCdnPools 对象池长度 " + listBasicCdnPools.size());
        List<User> list = listBasicCdnPools.poll();
        if (list == null) {
            list = new ArrayList<>();
        }
        list.clear();
        return list;
    }

    /**
     * 回收对象
     *
     * @param list
     */
    public static void offerListBasicCdnObj(List<User> list) {
        if (list != null) {
            list.clear();
            listBasicCdnPools.offer(list);
            System.out.println("=======>offer pool ListObj 对象池长度 " + listBasicCdnPools.size());
        }
    }
}
